package com.djf.djfclickhouse.controller;

import com.djf.djfclickhouse.entity.Order;
import com.djf.djfclickhouse.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/orders")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody Order order) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = orderService.createOrder(order);
            if (success) {
                result.put("code", 200);
                result.put("message", "订单创建成功");
                result.put("data", order);
            } else {
                result.put("code", 500);
                result.put("message", "订单创建失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "订单创建失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 批量创建订单
     */
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchCreateOrder(@RequestBody List<Order> orders) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = orderService.batchCreateOrder(orders);
            if (success) {
                result.put("code", 200);
                result.put("message", "批量创建订单成功");
                result.put("data", orders.size());
            } else {
                result.put("code", 500);
                result.put("message", "批量创建订单失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量创建订单失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据ID查询订单
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getOrderById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Order order = orderService.getOrderById(id);
            if (order != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", order);
            } else {
                result.put("code", 404);
                result.put("message", "订单不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询订单失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据订单号查询订单
     */
    @GetMapping("/orderNo/{orderNo}")
    public ResponseEntity<Map<String, Object>> getOrderByOrderNo(@PathVariable String orderNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            Order order = orderService.getOrderByOrderNo(orderNo);
            if (order != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", order);
            } else {
                result.put("code", 404);
                result.put("message", "订单不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询订单失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据用户ID查询订单列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getOrdersByUserId(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Order> orders = orderService.getOrdersByUserId(userId);
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", orders);
            result.put("total", orders.size());
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询用户订单失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 分页查询订单
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getOrdersWithPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer orderStatus) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Order> orders = orderService.getOrdersWithPage(pageNum, pageSize);
            long total = orderService.countOrders(userId, orderStatus);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", orders);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "分页查询订单失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 统计订单数量
     */
    @GetMapping("/count")
    public ResponseEntity<Map<String, Object>> countOrders(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer orderStatus) {
        Map<String, Object> result = new HashMap<>();
        try {
            long count = orderService.countOrders(userId, orderStatus);
            result.put("code", 200);
            result.put("message", "统计成功");
            result.put("data", count);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "统计订单数量失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam Integer orderStatus) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = orderService.updateOrderStatus(id, orderStatus);
            if (success) {
                result.put("code", 200);
                result.put("message", "订单状态更新成功");
            } else {
                result.put("code", 500);
                result.put("message", "订单状态更新失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "订单状态更新失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 删除订单（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteOrder(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = orderService.deleteOrder(id);
            if (success) {
                result.put("code", 200);
                result.put("message", "订单删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "订单删除失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "订单删除失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
    
    /**
     * 物理删除订单（谨慎使用）
     */
    @DeleteMapping("/{id}/physical")
    public ResponseEntity<Map<String, Object>> physicalDeleteOrder(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = orderService.physicalDeleteOrder(id);
            if (success) {
                result.put("code", 200);
                result.put("message", "订单物理删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "订单物理删除失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "订单物理删除失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
}